package com.moba.controller;

import com.alibaba.fastjson.JSONObject;
import com.moba.domain.*;
import com.moba.emums.*;
import com.moba.emums.roleUser.InitPassword;
import com.moba.emums.roleUser.UserType;
import com.moba.service.*;
import com.moba.utils.FieldFilter;
import com.moba.utils.ResultUtils;
import com.moba.utils.encrypt.DESPlusUtils;
import com.moba.utils.qrcode.CodeCreator;
import com.moba.utils.qrcode.CodeModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author liu, jia
 * @version 2019-02-20 09:59
 * @date 2019-02-20 09:59
 */
@RestController
@RequestMapping("/userInfo")
@Api(tags = {"用户接口"})
public class UserInfoController extends BaseController {

  @Resource UserInfoService userInfoService;
  @Resource UserRelationService userRelationService;
  @Resource UserRelationParService userRelationParServiceService;
  @Resource UserWalletService userWalletService;
  @Resource OrderInfoService orderInfoService;

  @ApiOperation(value = "获取列表")
  @GetMapping(value = "/list")
  public Object list(
      HttpServletRequest request,
      @ModelAttribute UserInfo entity,
      @RequestParam(name = "page") Integer page) {
    Map<String, Object> paramMap = WebUtils.getParametersStartingWith(request, FieldFilter.PREFIX);
    FieldFilter.setQuery(paramMap, entity);

    entity.setIsDel(YesOrNo.YES_OR_NO_0.getIndex());

    JSONObject jsonObject = new JSONObject();

    jsonObject.put("dataCount", userInfoService.getEntityCount(entity));

    entity.getRow().setCount(10);

    entity.getRow().setFirst((page - 1) * (entity.getRow().getCount()));
    List<UserInfo> entityList = userInfoService.getEntityPaginatedList(entity);

    if (null != entityList && entityList.size() > 0) {
      for (UserInfo temp : entityList) {

        // 调用钱包接口查询GHMI是否足够
        UserWallet userWallet = new UserWallet();
        userWallet.setUserId(temp.getId());
        userWallet = userWalletService.getEntity(userWallet);
        BigDecimal ghmi_total = new BigDecimal(10000);
        //        try {
        //          ghmi_total = new
        //                  BigDecimal(WalletHelp.getERC20Balance(userWallet.getEcr20Address()));
        //        } catch (Exception e) {
        //
        //        }
        temp.getMap().put("ghmiTotal", ghmi_total);

        String ghmiAddr = "";
        String usdtAddr = "";

        if (userWallet != null) {
          ghmiAddr = userWallet.getEcr20Address();
          usdtAddr = userWallet.getUsdtAddress();
        }

        temp.getMap().put("ghmiAddr", ghmiAddr);
        temp.getMap().put("usdtAddr", usdtAddr);

        // 查寻冻结订单
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setAddUserId(temp.getId());
        orderInfo.setOrderState(10);
        BigDecimal orderMoney = orderInfoService.getEntitySumMoneyBi(orderInfo);
        temp.getMap().put("orderMoney", orderMoney);
      }
    }
    jsonObject.put("entityList", entityList);
    jsonObject.put("userTypeList", super.parseEnmuToJSONArray(UserType.class, UserType.values()));
    jsonObject.put(
        "userLevelList", super.parseEnmuToJSONArray(UserLevel.class, UserLevel.values()));

    //        System.out.println(jsonObject);
    return ResultUtils.success(jsonObject);
  }

  @ApiOperation(value = "获取列表")
  @GetMapping(value = "/getGhumiAddr")
  public Object getGhumiAddr(HttpServletRequest request, @ModelAttribute UserInfo entity) {

    JSONObject jsonObject = new JSONObject();
    // 调用钱包接口查询GHMI是否足够
    UserWallet userWallet = new UserWallet();
    userWallet.setUserId(entity.getId());
    userWallet = userWalletService.getEntity(userWallet);
    if (null == userWallet) {
      return ResultUtils.error(CodeType.CODE_TYPE_104, "钱包不存在");
    }

    String ghmiAddr = "";
    String usdtAddr = "";

    ghmiAddr = userWallet.getEcr20Address();
    usdtAddr = userWallet.getUsdtAddress();

    jsonObject.put("ghmiAddr", ghmiAddr);
    jsonObject.put("usdtAddr", usdtAddr);

    return ResultUtils.success(jsonObject);
  }

  @ApiOperation(value = "保存")
  @PostMapping(value = "/save")
  public Object save(
      HttpServletRequest request, @RequestBody @Valid UserInfo entity, BindingResult result)
      throws Exception {

    //        String msgCode= request.getParameter("msgCode");
    logger.info("====msgCode:" + entity.getMsgCode());
    if (null == entity.getMsgCode()) {
      return ResultUtils.error(CodeType.CODE_TYPE_104, "手机动态码不可为空");
    }

    HttpSession session = request.getSession();
    System.out.println("====session:" + session);
    String mobileVeriCode = (String) session.getAttribute("mobileVeriCode");
    System.out.println("====mobileVeriCode:" + mobileVeriCode);

    //        if (!(entity.getMsgCode().equals(mobileVeriCode))) {
    //            return ResultUtils.error(CodeType.CODE_TYPE_104, "手机动态码填写有误");
    //        }

    if (null == entity.getPassword() || !checkPassword(entity.getPassword())) {
      return ResultUtils.error(CodeType.CODE_TYPE_104, "登录密码必须为字母加数字,不小于8位数");
    }
    if (null == entity.getSafePassword() || !checkSafePassword(entity.getSafePassword())) {
      return ResultUtils.error(CodeType.CODE_TYPE_104, "安全密码不可为空,并且是6位纯数字");
    }

    DESPlusUtils des = new DESPlusUtils();
    if (null == entity.getId()) {
      UserInfo ui1 = new UserInfo();
      if (StringUtils.isBlank(entity.getUserName())) {
        String msg = "用户名不能为空！";
        return ResultUtils.error(CodeType.CODE_TYPE_101, msg);
      }

      if (StringUtils.isBlank(entity.getYmid())) {
        String msg = "邀请人不能为空";
        return ResultUtils.error(CodeType.CODE_TYPE_101, msg);
      }

      UserInfo entityQueryHasExist = new UserInfo();
      entityQueryHasExist.getMap().put("ym_id", entity.getYmid());
      entityQueryHasExist.setIsDel(0);
      Integer recordCount = userInfoService.getEntityCount(entityQueryHasExist);
      if (recordCount.intValue() <= 0) {
        String msg = "未查询到该邀请人";
        return ResultUtils.error(CodeType.CODE_TYPE_101.getIndex(), msg);
      }

      if (recordCount > 0) {
        entityQueryHasExist = userInfoService.getEntity(entityQueryHasExist);
      }

      if (recordCount.intValue() > 1) {
        String msg = "上级用户重复，请联系管理员";
        return ResultUtils.error(CodeType.CODE_TYPE_101.getIndex(), msg);
      }

      ui1.setUserName(entity.getUserName());
      ui1.setIsDel(0);
      int count1 = userInfoService.getEntityCount(ui1);
      if (count1 > 0) {
        String msg = "用户名已存在！";
        return ResultUtils.error(CodeType.CODE_TYPE_101.getIndex(), msg);
      }

      if (StringUtils.isBlank(entity.getPassword())) {
        entity.setPassword(des.encrypt(InitPassword.INIT_PWD));
      } else {
        entity.setPassword(des.encrypt(entity.getPassword()));
      }

      UserInfo user_ymid = new UserInfo();
      user_ymid.getMap().put("ym_id", entity.getYmid());
      user_ymid.setIsDel(0);
      user_ymid = userInfoService.getEntity(user_ymid);
      entity.setYmid(user_ymid.getUserName()); // 全部保存用户名
      entity.getMap().put("insert_user_realtion", "true");

      entity.setSafePassword(des.encrypt(entity.getSafePassword()));
      entity.setUserType(UserType.USER_TYPE_2.getIndex());
      entity.setUserLevel(UserLevel.USER_LEVEL_200.getIndex());
      entity.setMobile(entity.getUserName());
      entity.setAddDate(new Date());

      // 赠送矿源
      BaseData a = new BaseData();
      a.setType(BaseDataType.BaseDataType_80.getIndex());
      a.setIsDel(0);
      a.getMap().put("thisDate", "true");
      List<BaseData> alist = baseDataService.getEntityList(a);
      if (null != alist) {
        entity.setOrderMoneySum(new BigDecimal(alist.get(0).getValue()));
      } else {
        // -1：没有则矿源额度无期限
        entity.setOrderMoneySum(new BigDecimal(-1));
      }

      userInfoService.createEntity(entity);

      UserInfo update = new UserInfo();

      String ctx = "";
      if (isLocal(request)) {
        ctx = super.getCtxPath(request, true);
      } else {
        ctx = super.getCtxPath(request, false);
      }
      ctx = super.getCtxPath(request, true);
      logger.info("===ctx:" + ctx);
      String Path =
          session.getServletContext().getRealPath(String.valueOf(File.separatorChar)); // 文件绝对路径
      logger.info("===Path:" + Path);
      //            String LogoFile = Path + "/files/logo.png";
      //            String LogoFile = "C:/Users/Administrator/Desktop/logo.png";
      String LogoFile = "D:/logo.png";

      File LogoFilea = new File(LogoFile);
      if (LogoFilea.exists()) {
        System.out.println("===logo路径存在");
      } else {
        System.out.println("===logo路径不存在");
      }

      logger.info("===ctx:" + ctx);

      String Jump_path = ctx + "/m/#/pages/login/register?ymid=" + entity.getMobile(); // 二维码跳转的路径
      logger.info("===Jump_path:" + Jump_path);
      String name = "分享二维码"; // 底部添加的文字
      String uploadDir = "files" + File.separator + "qrCode"; // 文件夹的名称
      String ctxDir = request.getServletContext().getRealPath(File.separator);
      if (!ctxDir.endsWith(File.separator)) {
        ctxDir = ctxDir + File.separator;
      }

      File savePath = new File(ctxDir + uploadDir);
      if (!savePath.exists()) {
        savePath.mkdirs();
      }

      String imgPath = ctxDir + uploadDir + File.separator + entity.getId() + ".png";
      File imgFile = new File(imgPath);

      if (imgFile.exists()) {
        imgFile.delete();
      }

      if (null != entity.getId()) {
        createQrcode(request, Path, Jump_path, LogoFile, name, uploadDir, entity.getId()); // 生成二维码
        update.setId(entity.getId());
        update.setQrcodePath(uploadDir + File.separator + 1 + ".png");
        userInfoService.updateEntity(update);
      } else {
        logger.info("===创建用户之后 id为null");
      }

    } else {
      if (StringUtils.isBlank(entity.getUserName()) || StringUtils.isBlank(entity.getPassword())) {
        String msg = "用户名或密码不能为空！";
        return ResultUtils.error(CodeType.CODE_TYPE_101.getIndex(), msg);
      }

      UserInfo user1 = new UserInfo();
      user1.setId(entity.getId());
      String oldName = userInfoService.getEntity(user1).getUserName();

      if (!oldName.equals(entity.getUserName())) {
        UserInfo ui1 = new UserInfo();
        ui1.setUserName(entity.getUserName());
        int count1 = userInfoService.getEntityCount(ui1);
        if (count1 > 0) {
          String msg = "用户名已存在！";
          return ResultUtils.error(CodeType.CODE_TYPE_101.getIndex(), msg);
        }
      }

      UserInfo user = new UserInfo();
      user.setId(entity.getId());
      String oldPwd = userInfoService.getEntity(user).getPassword();
      if (!oldPwd.equals(entity.getPassword())) {
        entity.setPassword(des.encrypt(entity.getPassword()));
      }
      entity.setUpdateDate(new Date());
      userInfoService.updateEntity(entity);
    }
    return ResultUtils.success();
  }

  @ApiOperation(value = "保存")
  @PostMapping(value = "/saveAdmin")
  public Object saveAdmin(
      HttpServletRequest request, @RequestBody @Valid UserInfo entity, BindingResult result)
      throws Exception {

    DESPlusUtils des = new DESPlusUtils();

    logger.info("entity.getPassword():" + entity.getPassword());
    if (StringUtils.isNotBlank(entity.getPassword())) {
      entity.setPassword(des.encrypt(entity.getPassword()));
    }
    entity.setUpdateDate(new Date());
    userInfoService.updateEntity(entity);

    return ResultUtils.success();
  }

  @ApiOperation(value = "查询单条记录")
  @GetMapping(value = "/{id}")
  public Object edit(@PathVariable(name = "id") Integer id) {

    UserInfo entity = new UserInfo();
    entity.setId(id);
    entity.setIsDel(YesOrNo.YES_OR_NO_0.getIndex());
    entity = userInfoService.getEntity(entity);
    if (null == entity) {
      return ResultUtils.error(CodeType.CODE_TYPE_102);
    }
    return ResultUtils.success(entity);
  }

  @ApiOperation(value = "充值用户矿源")
  @GetMapping(value = "/addOrderMoneySumSave")
  public Object addOrderMoneySumSave(
      Integer id, Integer addOrderMoneySum, String[] pks, Integer updateUserId) {

    logger.info("id:" + id);
    logger.info("addOrderMoneySum:" + addOrderMoneySum);
    logger.info("pks:" + StringUtils.join(pks));

    if (null == id && ArrayUtils.isEmpty(pks)) {
      return ResultUtils.error(CodeType.CODE_TYPE_101);
    }
    if (null == updateUserId) {
      return ResultUtils.error(CodeType.CODE_TYPE_101);
    }

    UserInfo updateUser = new UserInfo();
    updateUser.setId(updateUserId);
    updateUser.setIsDel(0);
    updateUser = userInfoService.getEntity(updateUser);
    if (null == updateUser) {
      return ResultUtils.error(CodeType.CODE_TYPE_104, "更新人不存在");
    }

    UserInfo entity = new UserInfo();
    if (null != id) {
      entity.setId(id);
    } else {
      entity.getMap().put("pks", pks);
      entity.getMap().put("pksStr", StringUtils.join(pks, ","));
    }

    entity.setUpdateUserId(updateUserId);
    entity.setUpdateDate(new Date());
    entity.getMap().put("updateUser", updateUser);
    entity.getMap().put("addOrderMoneySum", addOrderMoneySum);
    userInfoService.updateEntity(entity);
    return ResultUtils.success();
  }

  @ApiOperation(value = "根据id删除")
  @PostMapping(value = "/delete")
  public Object delete(Integer id, Integer delUserId, String[] pks) {

    if (null == id && ArrayUtils.isEmpty(pks)) {
      return ResultUtils.error(CodeType.CODE_TYPE_101);
    }
    UserInfo entity = new UserInfo();
    entity.setIsDel(YesOrNo.YES_OR_NO_1.getIndex());
    entity.setDelDate(new Date());
    entity.setDelUserId(delUserId);
    if (null != id) {
      entity.setId(id);
    } else {
      entity.getMap().put("pks", pks);
    }
    userInfoService.updateEntity(entity);
    return ResultUtils.success();
  }

  @ApiOperation(value = "获取团队列表")
  @GetMapping(value = "/teamList")
  public Object teamList(
      HttpServletRequest request,
      Integer userId,
      Integer teamLevel,
      String mobileLike,
      String ymidLike,
      @RequestParam(name = "page") Integer page) {
    JSONObject jsonObject = new JSONObject();

    UserRelationPar entity = new UserRelationPar();
    entity.setUserParId(userId);
    //    entity.getMap().put("my_lower_by_user_par_id", userId);
    entity.getMap().put("user_info_not_null", true);
    if (null != teamLevel) {
      //      entity.getMap().put("my_lower_by_level", teamLevel);
      entity.setUserParLevle(teamLevel);
    }

    if (StringUtils.isNotBlank(mobileLike)) {
      entity.getMap().put("mobileLike", mobileLike);
    }
    logger.info("====ymidLike:" + ymidLike);
    entity.getMap().put("ymidLike", ymidLike);

    Integer userCount = userRelationParServiceService.getEntityCount(entity);

    jsonObject.put("dataCount", userCount);

    entity.getRow().setCount(10);

    entity.getRow().setFirst((page - 1) * (entity.getRow().getCount()));
    List<UserRelationPar> entityList = userRelationParServiceService.getEntityPaginatedList(entity);

    //    List<UserInfo> dataList = new ArrayList<>();
    //    if (null != entityList && entityList.size() > 0) {
    //      for (UserRelationPar t : entityList) {
    //        UserInfo u = new UserInfo();
    //        u.setId(t.getUserId());
    //        u = userInfoService.getEntity(u);
    //        if (u != null) {
    //          dataList.add(u);
    //        }
    //      }
    //    }

    jsonObject.put("entityList", entityList);

    jsonObject.put("userTypeList", super.parseEnmuToJSONArray(UserType.class, UserType.values()));
    System.out.println(jsonObject);
    return ResultUtils.success(jsonObject);
  }

  @ApiOperation(value = "获取团队列表app")
  @GetMapping(value = "/appTeamList")
  public Object appTeamList(HttpServletRequest request, Integer userId) {
    JSONObject jsonObject = new JSONObject();

    UserInfo entity = new UserInfo();
    entity.setIsDel(YesOrNo.YES_OR_NO_0.getIndex());
    entity.setId(userId);

    jsonObject.put("dataCount", userInfoService.getEntityTeamCount(entity));

    //    entity.getRow().setCount(10);

    //    entity.getRow().setFirst((page - 1) * (entity.getRow().getCount()));

    List<UserInfo> entityList = userInfoService.getEntityTeamPaginatedList(entity);
    jsonObject.put("entityList", entityList);

    entity.getMap().put("leijiMoneyUser", "true");
    entityList = userInfoService.getEntityTeamPaginatedList(entity);
    jsonObject.put("leijiMoneyUserList", entityList);

    BigDecimal leijiMoneySum = userInfoService.getTeamLeijiMoneySum(entity);
    logger.info("leijiMoneySum:" + leijiMoneySum);
    jsonObject.put("leijiMoneySum", leijiMoneySum);

    return ResultUtils.success(jsonObject);
  }

  @ApiOperation(value = "更新密码")
  @GetMapping(value = "/updatePassword")
  public Object updatePassword(
      Integer userId, String oldPassword, String password, String password_) throws Exception {

    if (null == userId) {
      return ResultUtils.error(CodeType.CODE_TYPE_101);
    }
    if (StringUtils.isBlank(oldPassword)) {
      return ResultUtils.error(CodeType.CODE_TYPE_101);
    }
    if (StringUtils.isBlank(password)) {
      return ResultUtils.error(CodeType.CODE_TYPE_101);
    }
    if (StringUtils.isBlank(password_)) {
      return ResultUtils.error(CodeType.CODE_TYPE_101);
    }
    if (!StringUtils.equals(password, password_)) {
      return ResultUtils.error(CodeType.CODE_TYPE_104, "两次密码不一致");
    }

    DESPlusUtils des = new DESPlusUtils();

    UserInfo entity = new UserInfo();
    entity.setId(userId);
    entity.setIsDel(0);
    entity = userInfoService.getEntity(entity);
    if (null == entity) {
      return ResultUtils.error(CodeType.CODE_TYPE_104, "用户不存在或已被删除");
    }
    logger.info("des.decrypt(entity.getPassword()):" + des.decrypt(entity.getPassword()));
    logger.info("oldPassword:" + oldPassword);
    if (!StringUtils.equals(des.decrypt(entity.getPassword()), oldPassword)) {
      return ResultUtils.error(CodeType.CODE_TYPE_104, "原密码错误");
    }

    UserInfo update = new UserInfo();
    update.setId(entity.getId());
    update.setPassword(des.encrypt(password));
    userInfoService.updateEntity(update);

    entity = userInfoService.getEntity(entity);
    return ResultUtils.success(entity);
  }

  @ApiOperation(value = "更新密码")
  @GetMapping(value = "/updateSafePassword")
  public Object updateSafePassword(Integer userId, String safePassword, String safePassword_)
      throws Exception {

    if (null == userId) {
      return ResultUtils.error(CodeType.CODE_TYPE_101);
    }
    if (StringUtils.isBlank(safePassword)) {
      return ResultUtils.error(CodeType.CODE_TYPE_101);
    }
    if (StringUtils.isBlank(safePassword_)) {
      return ResultUtils.error(CodeType.CODE_TYPE_101);
    }
    if (!StringUtils.equals(safePassword, safePassword_)) {
      return ResultUtils.error(CodeType.CODE_TYPE_104, "两次密码不一致");
    }

    DESPlusUtils des = new DESPlusUtils();

    UserInfo entity = new UserInfo();
    entity.setId(userId);
    entity.setIsDel(0);
    entity = userInfoService.getEntity(entity);
    if (null == entity) {
      return ResultUtils.error(CodeType.CODE_TYPE_104, "用户不存在或已被删除");
    }
    UserInfo update = new UserInfo();
    update.setId(entity.getId());
    update.setSafePassword(des.encrypt(safePassword));
    userInfoService.updateEntity(update);

    entity = userInfoService.getEntity(entity);
    return ResultUtils.success(entity);
  }

  @ApiOperation(value = "绑定usdt地址")
  @GetMapping(value = "/bindUsdtAddr")
  public Object bindUsdtAddr(Integer userId, String msgCode, String usdtAddr, String safePassword)
      throws Exception {
    if (null == userId) {
      return ResultUtils.error(CodeType.CODE_TYPE_101);
    }
    if (StringUtils.isBlank(msgCode)) {
      return ResultUtils.error(CodeType.CODE_TYPE_101);
    }
    if (StringUtils.isBlank(usdtAddr)) {
      return ResultUtils.error(CodeType.CODE_TYPE_101);
    }
    if (StringUtils.isBlank(safePassword)) {
      return ResultUtils.error(CodeType.CODE_TYPE_101);
    }

    DESPlusUtils des = new DESPlusUtils();

    UserInfo entity = new UserInfo();
    entity.setId(userId);
    entity.setIsDel(0);
    entity = userInfoService.getEntity(entity);
    if (null == entity) {
      return ResultUtils.error(CodeType.CODE_TYPE_104, "用户不存在或已被删除");
    }

    logger.info("safePassword:" + safePassword);
    logger.info("entity.safePassword:" + des.decrypt(entity.getSafePassword()));
    if (!StringUtils.equals(des.decrypt(entity.getSafePassword()), safePassword)) {
      return ResultUtils.error(CodeType.CODE_TYPE_104, "安全密码不正确");
    }

    UserInfo update = new UserInfo();
    update.setId(entity.getId());
    update.setUsdtAddr(usdtAddr);
    userInfoService.updateEntity(update);

    entity = userInfoService.getEntity(entity);

    return ResultUtils.success(entity);
  }

  @ApiOperation(value = "保存")
  @PostMapping(value = "/sendMsgRegister")
  public Object sendMsgRegister(
      HttpServletRequest request, @RequestBody @Valid UserInfo entity, BindingResult result)
      throws Exception {

    if (null == entity.getUserName()) {
      return ResultUtils.error(CodeType.CODE_TYPE_101, "用户名不能为空！");
    }
    if (null == entity.getPassword()) {
      return ResultUtils.error(CodeType.CODE_TYPE_101, "密码不能为空！");
    }
    if (null == entity.getYmid()) {
      return ResultUtils.error(CodeType.CODE_TYPE_101, "邀请人不能为空！");
    }
    UserInfo a = new UserInfo();
    a.getMap().put("ym_id", entity.getUserName());
    a.setIsDel(0);
    int count = userInfoService.getEntityCount(a);
    if (count > 0) {
      return ResultUtils.error(CodeType.CODE_TYPE_104, "该手机号码已被注册！");
    }
    SendMessageController b = new SendMessageController();
    b.sendMsgCode(request, entity.getUserName(), SmsTemplate.sms_01);

    return ResultUtils.success();
  }

  @ApiOperation(value = "绑定usdt地址验证码")
  @PostMapping(value = "/sendMsgBindAddr")
  public Object sendMsgBindAddr(
      HttpServletRequest request, @RequestBody @Valid UserInfo entity, BindingResult result)
      throws Exception {

    if (null == entity.getId()) {
      return ResultUtils.error(CodeType.CODE_TYPE_101, "用户参数不正确！");
    }

    entity.setIsDel(0);
    int count = userInfoService.getEntityCount(entity);
    if (count == 0) {
      return ResultUtils.error(CodeType.CODE_TYPE_104, "用户不存在！");
    }
    entity = userInfoService.getEntity(entity);
    if (null == entity) {
      return ResultUtils.error(CodeType.CODE_TYPE_104, "用户不存在！");
    }

    SendMessageController b = new SendMessageController();
    b.sendMsgCode(request, entity.getMobile(), SmsTemplate.sms_01);

    return ResultUtils.success();
  }

  @ApiOperation(value = "发送重置密码验证码")
  @PostMapping(value = "/sendMsgForget")
  public Object sendMsgForget(
      HttpServletRequest request, @RequestBody @Valid UserInfo entity, BindingResult result)
      throws Exception {

    if (null == entity.getUserName()) {
      return ResultUtils.error(CodeType.CODE_TYPE_101, "手机号码不能为空！");
    }
    if (null == entity.getPassword()) {
      return ResultUtils.error(CodeType.CODE_TYPE_101, "密码不能为空！");
    }

    UserInfo a = new UserInfo();
    a.getMap().put("ym_id", entity.getUserName());
    a.setIsDel(0);
    int count = userInfoService.getEntityCount(a);
    if (count == 0) {
      return ResultUtils.error(CodeType.CODE_TYPE_104, "手机号码未被注册！");
    }

    SendMessageController b = new SendMessageController();
    b.sendMsgCode(request, entity.getUserName(), SmsTemplate.sms_01);

    return ResultUtils.success();
  }

  @ApiOperation(value = "重置密码")
  @PostMapping(value = "/forgetPassword")
  public Object forgetPassword(
      HttpServletRequest request, @RequestBody @Valid UserInfo entity, BindingResult result)
      throws Exception {

    if (null == entity.getUserName() || null == entity.getPassword()) {
      return ResultUtils.error(CodeType.CODE_TYPE_101);
    }
    if (null == entity.getMsgCode()) {
      return ResultUtils.error(CodeType.CODE_TYPE_101, "验证码为空");
    }

    DESPlusUtils des = new DESPlusUtils();
    UserInfo userInfo = new UserInfo();
    userInfo.getMap().put("ym_id", entity.getUserName());
    userInfo.setIsDel(0);
    userInfo = userInfoService.getEntity(userInfo);
    if (null == userInfo) {
      return ResultUtils.error(CodeType.CODE_TYPE_104, "用户不存在或已被删除");
    }

    UserInfo update = new UserInfo();
    update.setId(userInfo.getId());
    update.setPassword(des.encrypt(entity.getPassword()));
    userInfoService.updateEntity(update);

    return ResultUtils.success();
  }

  /**
   * 生成二维码图片
   *
   * @param Path 文件的绝对路径
   * @param Jump_path 二维码跳转的路径
   * @param name 底部添加的文字
   * @param Local_folders 要存文件夹的名称
   * @param comm_id 商品的id
   */
  public void createQrcode(
      HttpServletRequest request,
      String Path,
      String Jump_path,
      String Logo,
      String name,
      String Local_folders,
      int comm_id) {
    CodeCreator creator = new CodeCreator();
    CodeModel info = new CodeModel();
    info.setWidth(400);
    info.setHeight(400);
    info.setFontSize(30);
    info.setContents(Jump_path); // 二维码跳转的路径
    info.setLogoFile(new File(Logo)); // 商品的头像
    info.setDesc(name); // 底部添加的文字
    String ctxDir = request.getServletContext().getRealPath(File.separator);

    if (!ctxDir.endsWith(File.separator)) {
      ctxDir = ctxDir + File.separator;
    }
    File savePath = new File(ctxDir + Local_folders);
    if (!savePath.exists()) {
      savePath.mkdirs();
    }
    String imgPath = ctxDir + Local_folders + File.separator + comm_id + ".png";
    File imgFile = new File(imgPath);
    System.out.println("imgFile.getPath()" + imgFile.getPath());

    if (!imgFile.exists()) {
      creator.createCodeImage(
          info,
          Path + Local_folders + File.separator + comm_id + "." + info.getFormat()); // 本地储存的路径
    }
  }

  public boolean isLocal(HttpServletRequest request) {
    String ip = getIpAddr(request);
    logger.info("===ip:" + ip);
    if (("192.168.2.160,192.168.2.201,0:0:0:0:0:0:0:1").contains(ip)) {
      return true;
    }
    return false;
  }

  /**
   * @return ip
   * @author Li, Yuan
   */
  public String getIpAddr(HttpServletRequest request) {
    String ip = request.getHeader("x-forwarded-for");
    if (StringUtils.isNotBlank(ip)
        && !"unknown".equalsIgnoreCase(ip)
        && StringUtils.contains(ip, ",")) {
      ip = StringUtils.split(ip, ",")[0];
    }
    if ((ip == null) || (ip.length() == 0) || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("Proxy-Client-IP");
    }
    if ((ip == null) || (ip.length() == 0) || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if ((ip == null) || (ip.length() == 0) || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getRemoteAddr();
    }
    logger.info("===ip:" + ip);
    return ip;
  }

  @ApiOperation(value = "执行定时任务")
  @GetMapping(value = "/userLeveUp")
  public Object userLeveUp() {
    logger.info("===userLeveUp===start");
    BigDecimal yeji = new BigDecimal(String.valueOf(500000));

    // 成为k1的业绩
    BaseData base = new BaseData();
    base.setId(UserLevel.USER_LEVEL_201.getIndex());
    base = baseDataService.getEntity(base);
    if (base != null && base.getPreData() != null) {
      yeji = new BigDecimal(base.getPreData());
    }

    // 成为k2的业绩
    BigDecimal invit_count = new BigDecimal(3);
    BaseData baseData = new BaseData();
    baseData.setId(UserLevel.USER_LEVEL_202.getIndex());
    BaseData baseData_k2 = baseDataService.getEntity(baseData);
    if (baseData_k2 != null && baseData_k2.getPreData() != null) {
      invit_count = new BigDecimal(baseData_k2.getPreData());
    }

    BigDecimal yeji_k2 = yeji.multiply(invit_count);

    // 成为k3的业绩
    baseData.setId(UserLevel.USER_LEVEL_203.getIndex());
    BaseData baseData_k3 = baseDataService.getEntity(baseData);
    if (baseData_k3 != null && baseData_k3.getPreData() != null) {
      invit_count = new BigDecimal(baseData_k3.getPreData());
    }
    BigDecimal yeji_k3 = yeji_k2.multiply(invit_count);

    // 成为k4的业绩
    baseData.setId(UserLevel.USER_LEVEL_204.getIndex());
    BaseData baseData_k4 = baseDataService.getEntity(baseData);
    if (baseData_k4 != null && baseData_k4.getPreData() != null) {
      invit_count = new BigDecimal(baseData_k4.getPreData());
    }
    BigDecimal yeji_k4 = yeji_k3.multiply(invit_count);

    // 升级普通用户
    UserInfo user = new UserInfo();
    user.setIsDel(0);
    user.getMap().put("leiji_money_user_gt", yeji);
    user.getMap().put("user_level_lt", UserLevel.USER_LEVEL_201.getIndex());
    List<UserInfo> userList = userInfoService.getEntityList(user);

    if (null != userList && userList.size() > 0) {
      BaseData data = new BaseData();
      data.setType(BaseDataType.BaseDataType_70.getIndex());
      data.setLinkId(UserLevel.USER_LEVEL_201.getIndex());
      data = baseDataService.getEntity(data);

      BigDecimal levelUpPrice_rate = new BigDecimal(data.getValue());
      BigDecimal levelUpPrice_k1 = yeji.multiply(levelUpPrice_rate);

      for (UserInfo tempUser : userList) {

        UserRelation userRelation = new UserRelation();
        userRelation.setUserParId(tempUser.getId());
        int invite_count = userRelationService.getEntityCount(userRelation);
        if (invite_count >= Integer.valueOf(base.getValue())) { // 直推20人

          tempUser.setUserLevel(UserLevel.USER_LEVEL_201.getIndex());
          tempUser.setUpdateDate(new Date());
          // 同级奖励
          tempUser.getMap().put("send_tongji_price", true);
          userInfoService.updateEntity(tempUser);

          // 升级奖励
          userInfoService.updateBi(
              tempUser.getId(),
              tempUser.getId(),
              BiGetType.BI_GET_TYPE_60.getIndex(),
              BiType.BI_TYPE_300.getIndex(),
              BiChuOrRu.BI_CHU_OR_RU_1.getIndex(),
              levelUpPrice_k1,
              null);
        }
      }
    }

    // 升级k1,k2,k3,k4的用户
    UserInfo userInfo = new UserInfo();
    userInfo.setIsDel(0);
    userInfo.getMap().put("user_level_in", "201,202,203,204");
    List<UserInfo> list = userInfoService.getEntityList(user);

    if (null != list && list.size() > 0) {
      for (UserInfo tempUser : userList) {

        switch (tempUser.getUserLevel()) {
          case 201:
            boolean can_level_up1 =
                userInfoService.userLevelCount(
                    tempUser.getId(), UserLevel.USER_LEVEL_201.getIndex());
            if (can_level_up1) {
              tempUser.setUserLevel(UserLevel.USER_LEVEL_202.getIndex());
              tempUser.setUpdateDate(new Date());
              tempUser.getMap().put("send_tongji_price", true);
              userInfoService.updateEntity(tempUser);
              // 升级奖励
              BaseData data = new BaseData();
              data.setType(BaseDataType.BaseDataType_70.getIndex());
              data.setLinkId(UserLevel.USER_LEVEL_202.getIndex());
              data = baseDataService.getEntity(data);

              BigDecimal levelUpPrice_rate = new BigDecimal(data.getValue());
              BigDecimal levelUpPrice_k2 = yeji_k2.multiply(levelUpPrice_rate);

              userInfoService.updateBi(
                  tempUser.getId(),
                  tempUser.getId(),
                  BiGetType.BI_GET_TYPE_60.getIndex(),
                  BiType.BI_TYPE_300.getIndex(),
                  BiChuOrRu.BI_CHU_OR_RU_1.getIndex(),
                  levelUpPrice_k2,
                  null);
            }
            break;
          case 202:
            boolean can_level_up2 =
                userInfoService.userLevelCount(
                    tempUser.getId(), UserLevel.USER_LEVEL_202.getIndex());
            if (can_level_up2) {
              tempUser.setUserLevel(UserLevel.USER_LEVEL_203.getIndex());
              tempUser.setUpdateDate(new Date());
              tempUser.getMap().put("send_tongji_price", true);
              userInfoService.updateEntity(tempUser);
              // 升级奖励
              BaseData data = new BaseData();
              data.setType(BaseDataType.BaseDataType_70.getIndex());
              data.setLinkId(UserLevel.USER_LEVEL_203.getIndex());
              data = baseDataService.getEntity(data);

              BigDecimal levelUpPrice_rate = new BigDecimal(data.getValue());
              BigDecimal levelUpPrice_k3 = yeji_k3.multiply(levelUpPrice_rate);

              userInfoService.updateBi(
                  tempUser.getId(),
                  tempUser.getId(),
                  BiGetType.BI_GET_TYPE_60.getIndex(),
                  BiType.BI_TYPE_300.getIndex(),
                  BiChuOrRu.BI_CHU_OR_RU_1.getIndex(),
                  levelUpPrice_k3,
                  null);
            }

            break;
          case 203:
            boolean can_level_up3 =
                userInfoService.userLevelCount(
                    tempUser.getId(), UserLevel.USER_LEVEL_203.getIndex());
            if (can_level_up3) {
              tempUser.setUserLevel(UserLevel.USER_LEVEL_204.getIndex());
              tempUser.setUpdateDate(new Date());
              tempUser.getMap().put("send_tongji_price", true);
              userInfoService.updateEntity(tempUser);
              // 升级奖励
              BaseData data = new BaseData();
              data.setType(BaseDataType.BaseDataType_70.getIndex());
              data.setLinkId(UserLevel.USER_LEVEL_204.getIndex());
              data = baseDataService.getEntity(data);

              BigDecimal levelUpPrice_rate = new BigDecimal(data.getValue());
              BigDecimal levelUpPrice_k4 = yeji_k4.multiply(levelUpPrice_rate);

              userInfoService.updateBi(
                  tempUser.getId(),
                  tempUser.getId(),
                  BiGetType.BI_GET_TYPE_60.getIndex(),
                  BiType.BI_TYPE_300.getIndex(),
                  BiChuOrRu.BI_CHU_OR_RU_1.getIndex(),
                  levelUpPrice_k4,
                  null);
            }
            break;
          default:
            boolean can_level_up4 =
                userInfoService.userLevelCount(
                    tempUser.getId(), UserLevel.USER_LEVEL_204.getIndex());
            //            if (can_level_up4) {
            //              tempUser.setUserLevel(UserLevel.USER_LEVEL_205.getIndex());
            //              tempUser.setUpdateDate(new Date());
            //              tempUser.getMap().put("send_tongji_price", true);
            //              userInfoService.updateEntity(tempUser);
            //
            //              // 升级奖励
            //              BaseData data = new BaseData();
            //              data.setType(BaseDataType.BaseDataType_70.getIndex());
            //              data.setLinkId(UserLevel.USER_LEVEL_205.getIndex());
            //              data = baseDataService.getEntity(data);
            //
            //              BigDecimal levelUpPrice_rate = new BigDecimal(data.getValue());
            //              BigDecimal levelUpPrice_k5 = yeji_k5.multiply(levelUpPrice_rate);
            //
            //              userInfoService.updateBi(
            //                  tempUser.getId(),
            //                  tempUser.getId(),
            //                  BiGetType.BI_GET_TYPE_60.getIndex(),
            //                  BiType.BI_TYPE_300.getIndex(),
            //                  BiChuOrRu.BI_CHU_OR_RU_1.getIndex(),
            //                  levelUpPrice_k5,
            //                  null);
            //            }
            break;
        }
      }
    }
    logger.info("===userLeveUp===end");
    return ResultUtils.success();
  }

  @ApiOperation(value = "获取用户信息")
  @GetMapping(value = "/getUserInfo")
  public Object getUserInfo(Integer userId) throws Exception {

    if (null == userId) {
      return ResultUtils.error(CodeType.CODE_TYPE_101);
    }

    UserInfo entity = new UserInfo();
    entity.setId(userId);
    entity.setIsDel(0);
    entity = userInfoService.getEntity(entity);
    if (null == entity) {
      return ResultUtils.error(CodeType.CODE_TYPE_104, "用户不存在或已被删除");
    }

    BaseData a = new BaseData();
    //    a.setType(BaseDataType.BaseDataType_200.getIndex());
    a.setId(entity.getUserLevel());
    a.setIsDel(0);
    a = baseDataService.getEntity(a);
    entity.getMap().put("userLevelName", a.getTypeName());

    return ResultUtils.success(entity);
  }

  @ApiOperation(value = "测试-插入用户")
  @GetMapping(value = "/testUser")
  public Object testUser(Integer count, String ymid) {

    logger.info("count:" + count);
    if (null == count) {
      count = 1;
    }

    UserInfo a = new UserInfo();
    if (StringUtils.isNotBlank(ymid)) {
      a.getMap().put("ymid", ymid);
    }

    a.getMap().put("insert_user_test", count);
    userInfoService.createEntity(a);

    return ResultUtils.success();
  }
}
